import { find, ImageAsset, instantiate, math, Prefab, resources, SpriteFrame, sys, Texture2D } from "cc";
import { losChannelWeb } from "./losChannelWeb";
import loskc from "./loskc";
import { nativeInterAd } from "db://assets/scripts/ui/nativeInterAd";



export class losChannelHw extends losChannelWeb {

    //堆叠我最6 ks683421246509608689
    paraMap: Map<String, string> = new Map([
        ['bannerId', 'j1pcnpx5tu'], // 正式 d7r6634ewb    测试 j1pcnpx5tu
        ['interId', 'testu7m3hc4gvm'],  // 正式 f95hqv42qn   测试 u7m3hc4gvm
        ['videoAd', 'u2k89ub7vq'],  // 正式 n9gze4ijmp   测试 u2k89ub7vq
        // ['htId', '2007752'],
        ['customAd', 'testb4znbuh3n2'],
        ['ctrlId', '69099335088d094169eb8bb2'],
        ['appId', '115575621'],
        ['gid', ''],
    ]);

    channelObj: any = (window as any).qg
    ruanzhu: string = '著作权人:南京天豆互动网络科技有限公司\n登记号:2025SA0149141';
    companyName: string = '南京桔柚檬网络科技有限公司';
    gameName: string = '我来当老大';
    videoArr1: string[] = ["u2k89ub7vq", "u2k89ub7vq", "u2k89ub7vq"];
    videoArr2: string[] = ["u2k89ub7vq", "u2k89ub7vq", "u2k89ub7vq"];
    videoArr3: string[] = ["u2k89ub7vq", "u2k89ub7vq", "u2k89ub7vq"];

    exit(): void {
        this.channelObj.exitApplication();

    }

    getSysInfo() {
        if (!this.sysInfo && sys.platform != sys.Platform.DESKTOP_BROWSER) {
            this.sysInfo = this.channelObj.getSystemInfoSync();
        }
        return this.sysInfo;
    }
    OptionsSync = null
    isBuyUser = false
    pValue = ""
    timeIndex = 1
    loadingProgessArray = []
    loadingFlagArray = []
    init() {
        this.reLoadVideo();


        // this.channelObj.onHide(() => {
        //     if (this.showVideoInterFlag) {
        //         this.showVideoInterFlag = false
        //         this.playCustom()

        //     }
        // })

        const me = this;
        const ctrlId = me.getPara('ctrlId');

        if (ctrlId) {
            try {
                this.OptionsSync = me.channelObj.getLaunchOptionsSync()
                console.log("启动信息", JSON.stringify(this.OptionsSync))
                let query: string = this.OptionsSync.query

                if (query && query.indexOf("callback") >= 0) {
                    console.log("query信息", query)
                    let callback: String = JSON.parse(query).callback
                    console.log("callback信息", callback)
                    if (callback) {
                        this.pValue = callback.split('&')[2]
                        if (this.pValue.length > 10) {
                            console.log("校验成功", this.pValue)
                            this.isBuyUser = true
                        }
                        console.log("有callback", this.pValue)
                    } else {
                        console.log("没有callback")
                    }
                } else {
                    this.isBuyUser = false
                }
            } catch {
                console.error("买量代码出现错误")
            }

            console.log("是不是买量用户", this.isBuyUser)
            // if (query.userEntry == 'app' || query.userEntry == 'quickapp') {
            //     this.isBuyUser = false
            // } else {
            //     this.isBuyUser = true
            // }
            //this.isBuyUser = false
            let reqData = null
            if (this.isBuyUser) {
                reqData = {
                    'id': ctrlId,
                    'fromid': 1,
                }
            } else {
                reqData = {
                    'id': ctrlId

                }
            }
            try {
                if (this.isBuyUser) {
                    setTimeout(() => {
                        loskc.eventReport("游戏时间10")
                        console.error("1游戏时间10")
                    }, 10 * 1000);
                    setTimeout(() => {
                        loskc.eventReport("游戏时间20")
                        console.error("1游戏时间20")
                    }, 20 * 1000);
                    setInterval(() => {
                        loskc.eventReport("游戏时间" + this.timeIndex * 30)
                        console.error("1游戏时间" + this.timeIndex * 30)
                        this.timeIndex++
                    }, 30 * 1000);
                } else {
                    setTimeout(() => {

                        console.error("游戏时间10")
                    }, 10 * 1000);
                    setTimeout(() => {

                        console.error("游戏时间20")
                    }, 20 * 1000);
                    setInterval(() => {

                        console.error("游戏时间" + this.timeIndex * 30)
                        this.timeIndex++
                    }, 30 * 1000);
                }
            } catch {
                console.error("游戏时间上报错误")
            }
            loskc.jpost('https://ga.gametdd.com/adCtrl/agd/conf', reqData, (err, re) => {
                if (err) {
                    console.error("错误: ", err);
                    return;
                }
                if ('' + re.code !== '0') {
                    console.error('返回值错误:' + re);
                    return;
                }
                me.ctrl = re.data;
                console.error('====>111返回', me.ctrl);
                // let p5: String = this.ctrl['p4']

                // this.loadingProgessArray = p5.split('，')
                // for (let i = 0; i < this.loadingProgessArray.length; i++) {
                //     this.loadingFlagArray.push(true)
                // }

            });

            // try {

            //     this.channelObj.onHide(
            //         () => {
            //             if (this.showVideoInterFlag) {
            //                 this.showVideoInterFlag = false
            //                 this.playCustom()

            //             }
            //             console.error("onHide", this.rewordVideo, this.onHideVideo, this.loadVideo, this.existInter, this.NoHideVideo)
            //             if (this.rewordVideo || this.onHideVideo || this.loadVideo || this.NoHideVideo) {
            //                 return
            //             } else {

            //                 if (this.getCtrl('p19')) {
            //                     if (!this.existInter) {
            //                         console.error("onhide播放视频")
            //                         this.onHideVideos(this.getCtrl('p19'))
            //                     }
            //                 }
            //             }
            //         }
            //     );

            // } catch {
            //     console.error("onHide出现问题")
            // }
        }
        this.getOAId()
    }
    existInter = false
    NoHideVideo = true
    hwOAID = null
    onHideVideo = false
    rewordVideo = false
    onhide = false
    getOAId() {
        if (sys.platform == sys.Platform.DESKTOP_BROWSER) {
            return
        }
        //获取设备oaid
        if (window["qg"].getOAID) {
            window["qg"].getOAID({
                success: (ret) => {
                    let oaid = ret["oaid"];
                    console.log("qg.getOAID success :" + JSON.stringify(ret));
                    console.log("======oaid oaid oaid: ====", oaid);
                    console.log("======p:====", this.pValue);
                    this.hwOAID = oaid;
                    const reqData = { 'oaid': this.hwOAID, 'p': this.pValue };
                    loskc.jpost('https://ga.gamejym.com/fcm/adTrack/hw_active', reqData, (err, re) => {
                        if (err) {
                            console.error(err);
                            return;
                        }
                        console.error('关键行为激活', JSON.stringify(re));
                    });
                },
                fail: (errMsg, errCode) => {
                    console.error("qg.getOAID fail " + errCode + ': ' + errMsg)
                },
                complete: () => {
                    console.error("qg.getOAID complete")
                }
            })
        }
    }
    sendReportActive(adKey, isbanner = false) {
        if (!this.hwOAID) {
            console.error("this.hwOAID为空")
            return;
        }
        const reqData = { 'oaid': this.hwOAID, 'p': this.pValue };
        let that = this
        loskc.jpost('https://ga.gamejym.com/fcm/adTrack/hw_addiction', reqData, (err, re) => {
            if (err) {
                console.error(err);
                return;
            }
            console.log('reportAdClick:', adKey)
            if (isbanner) {
                that.nativeBanner.reportAdClick({
                    adId: adKey,
                })
            } else {
                that.nativeAd.reportAdClick({
                    adId: adKey,
                })
            }

            console.error('关键行为插屏返回', JSON.stringify(re));
        });
    }
    getRandomFloat(min: number, max: number): number {
        return Math.random() * (max - min) + min;
    }

    loadingVideoChangeFlag = true
    loadingVideo(times) {
        let that = this
        try {
            if (times === 0) {

                //this.loadVideo = false

                return; // 终止递归
            }
            if (this.loadingVideoChangeFlag) {
                this.loadingVideoChangeFlag = false
                this.loadVideo = true
                console.error("---------------------loadingVideo", times, 1000 * 1 * (times + 1) + 500)
                setTimeout(() => {
                    this.loadingVideoChangeFlag = true
                    this.loadVideo = false

                }, 1000 * 1 * (times + 1) + 1000);
            }


            this.showManyVideo(() => {

            }, () => {
                setTimeout(() => {
                    this.loadingVideo(times - 1); // 递归调用
                }, 1000);
            }
            );
        } catch {
            console.error("loadingVideo")
            this.loadVideo = false

            return
        }

    }
    loadVideo = false
    onHideChangeFlag = true
    onHideVideos(times) {
        let that = this
        try {
            if (times == 0) {
                // this.onHideVideo = false
                return; // 终止递归
            }
            if (this.onHideChangeFlag) {
                this.onHideChangeFlag = false
                this.onHideVideo = true
                console.error("---------------------onHideVideos", times)
                setTimeout(() => {
                    this.onHideVideo = false
                    this.onHideChangeFlag = true

                }, 1000 * this.getCtrl("p7") * (this.getCtrl('p19') + 1) + 1500);
            }

            this.showManyVideo(() => {
                // that.onHideVideo = false
            }, () => {
                setTimeout(() => {
                    that.onHideVideos(times - 1); // 递归调用
                }, 1000 * that.getCtrl("p7"));

            }
            );
        } catch {
            console.error("onHideVideos")
            this.onHideVideo = false
            return
        }
    }
    showManyVideo(succ, end = null): void {
        if (sys.platform == sys.Platform.DESKTOP_BROWSER) {
            console.log("观看广告")
            succ && succ()
            end && end()
            return
        }
        console.log("观看广告")
        //this.rewordVideo = true
        this.videoEnd = end
        this.videoSuccess = succ
        this.rewardedVideoAd.show();
        this.rewardedVideoAd.load();
    }
    transformString(input: string): string {
        // 将小写字母转换为大写，数字保持不变
        let transformedStr = input.replace(/[a-z]/g, char => char.toUpperCase());
        // 在每两个字符之间插入 ':'
        return transformedStr.split('').reduce((acc, char, index) => {
            return acc + char + ((index % 2 === 1 && index !== transformedStr.length - 1) ? ':' : '');
        }, '');
    }
    qgLogin(success, fail) {
        if (sys.platform == sys.Platform.DESKTOP_BROWSER) {
            success()
            return
        }
        const me = this;
        console.log("Sign-in", this.getPara('appId'));
        this.channelObj.gameLoginWithReal({
            forceLogin: 1,
            appid: me.getPara('appId'),
            success: function (data) {
                // 登录成功后，可以存储帐号信息。             
                console.log(" game login with real success:" + JSON.stringify(data));
                //me.channelUserId = data.playerId;
                success && success("login succ");
                // if (pzaLocalData.data.playerNick != null && pzaLocalData.data.playerAvatar != null) {
                //     return;
                // }
                // me.sendUserInfo({nickName:data.displayName,avatarUrl:data.imageUri})
            },
            fail: function (data, code) {
                console.log("game login with real fail:" + data + ", code:" + code);
                //根据状态码处理游戏的逻辑。
                //状态码为7004或者2012，表示玩家取消登录。
                //此时，建议返回游戏界面，可以让玩家重新进行登录操作。
                if (code == 7004 || code == 2012) {
                    console.log("玩家取消登录，返回游戏界面让玩家重新登录。")
                    fail && fail("login fail");
                }
                //状态码为7021表示玩家取消实名认证。
                //在中国大陆的情况下，此时需要禁止玩家进入游戏。
                if (code == 7021) {
                    console.log("The player has canceled identity verification. Forbid the player from entering the game.")
                    fail && fail("login fail");
                }
            }
        })
    }
    doAction(actName: any, paras: any) {
        if (paras[0] == 'hw') {
            if (actName == 'loading中强弹视频') {

            } else {
                console.error("hw策略名字", actName, "参数", paras)
            }
            //console.error("hw策略名字", actName, "参数", paras)
            if (actName == '所有二级界面弹出插屏') {
                let isOpen = this.getCtrl('p1')
                if (isOpen) {
                    this.showInter()
                }
            } else if (actName == '常驻banner') {
                let isOpen = this.getCtrl('p2') > Math.random() * 100
                if (isOpen && this.A) {
                    this.A = false
                    setTimeout(() => {
                        this.showBanner()
                    }, 2000)

                }
            } else if (actName == 'loading中强弹视频') {
                let isOpen = this.getCtrl('p3')

                if (isOpen) {

                    for (let i = 0; i < this.loadingProgessArray.length; i++) {
                        if (paras[1] > parseFloat(this.loadingProgessArray[i]) / 100 && this.loadingFlagArray[i]) {
                            this.loadingFlagArray[i] = false

                            this.showVideo(
                                () => {

                                }
                            );
                            break
                        }
                    }
                }
            } else if (actName == "loading结束强弹视频广告") {

                let isOpen = this.getCtrl('p5')
                if (isOpen) {
                    this.loadingVideo(this.getCtrl('p5'))
                }
                setTimeout(() => {
                    this.NoHideVideo = false
                }, 500);
            }
            // else if (actName == '插屏一定会被点击') {
            //     let isOpen = this.getCtrl("p18") > Math.random() * 100
            //     console.log("插屏一定会被点击", isOpen)
            //     if (isOpen) {
            //         paras[1](true)
            //     } else {
            //         paras[1](false)
            //     }
            // } 
            else if (actName == '插屏间隔') {
                setTimeout(() => {
                    this.canShowInter = true
                    console.error("插屏间隔结束")
                }, 1000);
            } else if (actName == '有插屏') {
                this.existInter = true
            } else if (actName == '无插屏') {
                setTimeout(() => {
                    this.existInter = false
                }, 2000);

            } else if (actName == '进入游戏弹三个叠加为一组的视频') {
                let isOpen = this.getCtrl('p6')
                if (isOpen && this.B) {
                    this.B = false
                    this.doubleStackVideo()
                    setInterval(() => {
                        if (this.getCtrl('p6') > math.random() * 100) {
                            this.doubleStackVideo()
                        }
                    }, 10000);
                }
            }
        }
    }
    loopInterval = null;
    count = 0
    A = true
    B = true
    doubleStackVideo(end = null) { //双叠视频
        if (sys.platform == sys.Platform.DESKTOP_BROWSER) {
            console.log("双叠视频")
            end && end()
            return
        }
        console.log("双叠视频")
        // this.rewordVideo = true
        this.videoEnd1 = end
        // //this.videoSuccess = succ
        // this.videoEnd = end
        this.rewardedVideoAd.show();
        this.rewardedVideoAd1.show();
        this.rewardedVideoAd1.load();
        this.rewardedVideoAd.load();


        //end && end()



    }
    videoStackInterFlag = false
    videoStackInter(end = null) { //视频叠插屏
        console.error("视频叠插屏")
        this.videoEnd2 = end
        // this.rewordVideo = true
        this.showVideoInterFlag = true
        this.rewardedVideoAd2.show();
        this.rewardedVideoAd2.load();


    }
    groupCombie(times) {
        if (times == 0) {
            return
        }
        let isOpen = this.getCtrl('p8') > Math.random() * 100
        if (true) {
            console.error('参数', JSON.stringify(this.rewardedVideoAd), JSON.stringify(this.rewardedVideoAd1), JSON.stringify(this.rewardedVideoAd2))
            this.doubleStackVideo(() => {

                console.log("双叠视频结束")
                //if (this.getCtrl('p9') > Math.random() * 100) {
                if (true) {
                    this.videoStackInter(() => {
                        console.log("视频叠插屏结束")
                        this.groupCombie(times - 1)
                    }
                    )
                }
            })

        }
    }

    firstIn = true
    clickTime = 0
    clickTime1 = 0
    reciveReward() {
        localStorage.setItem('reciveRewardDate', Date.now().toString());
    }
    isNewDay(timeA: number): boolean {
        if (timeA <= 0) {
            return true;
        }
        const d1 = new Date(timeA);
        const d2 = new Date();
        if (d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth() && d1.getDate() === d2.getDate()) {
            return false;
        }
        return true;
    }
    //侧边栏有效吗
    checkSliderBarIsAvailable(a) {

        this.channelObj.checkSliderBarIsAvailable({
            success: (result) => {
                console.error(
                    "侧边栏调用成功: " + JSON.stringify(result));
                a && a(result.available)
            },
            fail: (result) => {
                console.error(
                    "侧边栏调用失败: " + JSON.stringify(result));
                a && a(false)
            },
        })

    }
    reciveLoginReward() {
        localStorage.setItem('reciveLoginRewardDate', Date.now().toString());
    }
    isLoginReWard() {
        if (!localStorage.getItem('reciveLoginRewardDate') || this.isNewDay(Number(localStorage.getItem('reciveLoginRewardDate')))) {
            console.error("新的一天")
            return true
        } else {
            return false
        }
    }
    showNoRewardVideo() {
    }
    private insertAD: any = null;
    canShowInter = true
    nativeAd = null;
    adId = null
    showInter(isForce?: boolean, style?: any): void {

        if (!this.canShowInter) {
            console.log("插屏间隔中")
            return
        }
        if (find("Canvas/UI/NativeInterAdLong")) {
            console.log("Canvas/UI/NativeInterAdLong")
            return
        }
        if (find("Canvas/UI/NativeInterAd")) {
            console.log("Canvas/UI/NativeInterAd")
            return
        }
        this.canShowInter = false
        // setTimeout(() => {
        //     if (cc.find("Canvas/UI/NativeInterAd")) {
        //     } else {
        //         this.canShowInter = true
        //     }
        // }, 2000);
        if (sys.platform == sys.Platform.DESKTOP_BROWSER) {
            console.log("观看插屏")
            //resources.load("NativeInterAd", Prefab, (err, prefab: Prefab) => {
            // let node = instantiate(prefab)
            let remoteUrl = 'https://contentcenter-drcn.dbankcdn.cn/img/pub_17/PPS_realtimeimage_100_1/37/v3/B2AaVqw1QQqxRVxji7_sDw/xsLFICnoSCyzi_9SruJXKw.png/__source__.jpg'

            this.loadPics(remoteUrl, null)
            // node.getComponent(nativeInterAd).init(null, null, null, null, null)
            // node.parent = find("UICanvas")
            //})
            return
        }
        // console.log("展示插屏", this.channelObj.getProvider());
        let that = this
        this.nativeAd = this.channelObj.createNativeAd({
            adUnitId: this.getPara("interId"),
            success: function (code) {
                console.log("loadNativeAd loadNativeAd : success");
            },
            fail: function (data, code) {
                console.log("loadNativeAd loadNativeAd fail: " + data + "," + code);
            },
            complete: function () {
                console.log("loadNativeAd loadNativeAd : complete");
            }
        });
        this.nativeAd.offLoad();
        this.nativeAd.onLoad(function (test) {
            console.log("ad demo loadNativeAd onLoad NativeAd enter length : " + test.adList.length);
            console.log(JSON.stringify(test));
            var imgUrlList = test.adList[0].imgUrlList;
            console.log("ad demo : loadNativeAd onLoad imgUrlList : " + imgUrlList);
            sys.localStorage.setItem("ImageList", imgUrlList);
            that.loadPics(imgUrlList, test)

        });
        this.nativeAd.offError();
        this.nativeAd.onError(function (test) {

            console.log("ad demo : loadNativeAd onError enter" + test.errCode);
            console.log("ad demo : loadNativeAd onError enter" + test.errMsg);
            that.canShowInter = true
            that.nativeAd.destroy()
        });
        this.adId = this.nativeAd.load();
    }
    loadPics(imgUrlList, test) {
        // console.log('loadPics')
        //remoteUrl 获取到的图片地址
        let remoteUrl = imgUrlList
        let type = '.jpg';
        if (remoteUrl.indexOf('.png') != -1) {
            type = '.png';
        } else if (remoteUrl.indexOf('.jpg') != -1) {
            type = '.jpg';
        } else if (remoteUrl.indexOf('.jpeg') != -1) {
            type = '.jpeg';
        }
        const img = new Image();
        img.src = remoteUrl;
        img.crossOrigin = 'anonymous';
        img.onload = (e) => {
            let texture = new Texture2D()
            texture.image = new ImageAsset(img)
            let _frame = new SpriteFrame()
            _frame.texture = texture
            console.log("-------------------", texture.width, texture.height)
            if (test) {
                if (texture.width > texture.height) {
                    resources.load("NativeInterAd", Prefab, (err, prefab: Prefab) => {
                        let node = instantiate(prefab)
                        node.getComponent(nativeInterAd).init(test.adList[0].adId, _frame, test.adList[0].title, test.adList[0].source, test.adList[0].clickBtnTxt)
                        node.parent = find("UICanvas")
                    })
                } else {
                    resources.load("NativeInterAd", Prefab, (err, prefab: Prefab) => {
                        let node = instantiate(prefab)
                        node.getComponent(nativeInterAd).init(test.adList[0].adId, _frame, test.adList[0].title, test.adList[0].source, test.adList[0].clickBtnTxt)
                        node.parent = find("UICanvas")
                    })
                }
            } else {
                resources.load("NativeInterAd", Prefab, (err, prefab: Prefab) => {
                    let node = instantiate(prefab)
                    node.getComponent(nativeInterAd).init(null, _frame, null, null, null)
                    node.parent = find("UICanvas")
                })
            }


        }
    }
    nativeBanner
    reportAdShow(adKey: string, isbanner = false): void {
        const reqData = { 'oaid': this.hwOAID, 'p': this.pValue };
        loskc.jpost('https://ga.gamejym.com/fcm/adTrack/hw_adShow', reqData, (err, re) => {
            if (err) {
                console.error(err);
                return;
            }
            console.error('关键行为展示', JSON.stringify(re));
        });
        console.log('reportAdShow:', adKey, isbanner)
        if (isbanner) {
            this.nativeBanner.reportAdShow({
                adId: adKey
            })
        } else {
            this.nativeAd.reportAdShow({
                adId: adKey
            })
        }
    }

    reportAdClick(adKey: string, isbanner = false): void {

        this.sendReportActive(adKey, isbanner)
    }
    sendReportVideoActive(isEnd) {
        if (!this.hwOAID) {
            console.error("this.hwOAID为空")
            return;
        }
        const reqData = { 'oaid': this.hwOAID, 'p': this.pValue, 'isEnd': isEnd };
        let that = this
        loskc.jpost('https://ga.gamejym.com/fcm/adTrack/hw_addiction', reqData, (err, re) => {
            if (err) {
                console.error(err);
                return;
            }

            console.error('关键视频回传', JSON.stringify(re));
        });
    }

    rewardedVideoAd;
    rewardedVideoAd1;
    rewardedVideoAd2;
    videoSuccess = null
    videoEnd = null
    videoSuccess1 = null
    videoEnd1 = null
    videoSuccess2 = null
    videoEnd2 = null
    videIndex: number = 0;
    videIndex1: number = 0;
    videIndex2: number = 0;

    showAdSucCnt: number = 0;
    reLoadVideo2() {
        if (sys.platform == sys.Platform.DESKTOP_BROWSER) {
            return
        }
        this.rewardedVideoAd2 = this.channelObj.createRewardedVideoAd({
            adUnitId: this.getPara('videoAd'),
            success: (code) => {
                console.log("ad demo : loadAndShowVideoAd2 createRewardedVideoAd success");
            },
            fail: (data, code) => {
                console.log("ad demo : loadAndShowVideoAd2 createRewardedVideoAd fail: " + data + "," + code);
            },
            complete: () => {
                console.log("ad demo : loadAndShowVideoAd2 createRewardedVideoAd complete");
            }
        });
        this.rewardedVideoAd2.offLoad()
        this.rewardedVideoAd2.onLoad(() => {
            console.log('ad demo2 :ad loaded.')
        })
        this.rewardedVideoAd2.offError()
        this.rewardedVideoAd2.onError((e) => {
            console.error('load ad error2:' + JSON.stringify(e));
            const errCode = e.errCode
            const errMsg = e.errMsg
            //this.rewordVideo = false
            // this.channelObj.showToast({
            //     message: '广告正在加载中，请稍等'
            // });
            this.videoEnd2 && this.videoEnd2()
            if (this.videIndex2 < 2) {
                this.videIndex2++
            } else {
                this.videIndex2 = 0
            }
            if (this.videIndex2 == 0) {
                setTimeout(() => {
                    this.reLoadVideo2()
                }, 5000);
            } else {
                this.reLoadVideo2()
            }

        })
        this.rewardedVideoAd2.offClose()
        this.rewardedVideoAd2.onClose((res) => {
            // if(!this.rewardedVideoAd) return
            // this.rewardedVideoAd.offClose(null);
            console.log('ad onClose2: ' + res.isEnded)
            //this.rewordVideo = false
            this.sendReportVideoActive(res.isEnded)
            // this.rewardedVideoAd.offLoad(null);
            if (res && res.isEnded || res === undefined) {
                console.log('播放激励视频结束，给予奖励2')
                this.videoSuccess2 && this.videoSuccess2()
                this.videoEnd2 && this.videoEnd2()
            } else {
                console.log('播放没结束，不给予奖励2')
                this.videoEnd2 && this.videoEnd2()
            }

        })
        this.rewardedVideoAd2.load()
    }
    reLoadVideo1() {
        if (sys.platform == sys.Platform.DESKTOP_BROWSER) {
            return
        }
        this.rewardedVideoAd1 = this.channelObj.createRewardedVideoAd({
            adUnitId: this.getPara('videoAd'),
            success: (code) => {
                console.log("ad demo : loadAndShowVideoAd1 createRewardedVideoAd success");
            },
            fail: (data, code) => {
                console.log("ad demo : loadAndShowVideoAd1 createRewardedVideoAd fail: " + data + "," + code);
            },
            complete: () => {
                console.log("ad demo : loadAndShowVideoAd1 createRewardedVideoAd complete");
            }
        });
        this.rewardedVideoAd1.offLoad()
        this.rewardedVideoAd1.onLoad(() => {
            console.log('ad demo1 :ad loaded.')
        })
        this.rewardedVideoAd1.offError()
        this.rewardedVideoAd1.onError((e) => {
            console.error('load ad error1:' + JSON.stringify(e));
            const errCode = e.errCode
            const errMsg = e.errMsg
            // this.rewordVideo = false
            // this.channelObj.showToast({
            //     message: '广告正在加载中，请稍等'
            // });
            this.videoEnd1 && this.videoEnd1()
            if (this.videIndex1 < 2) {
                this.videIndex1++
            } else {
                this.videIndex1 = 0
            }
            if (this.videIndex1 == 0) {
                setTimeout(() => {
                    this.reLoadVideo1()
                }, 5000);
            } else {
                this.reLoadVideo1()
            }

        })
        this.rewardedVideoAd1.offClose()
        this.rewardedVideoAd1.onClose((res) => {
            // if(!this.rewardedVideoAd) return
            // this.rewardedVideoAd.offClose(null);
            console.log('ad onClose1: ' + res.isEnded)
            //this.rewordVideo = false
            this.sendReportVideoActive(res.isEnded)
            // this.rewardedVideoAd.offLoad(null);
            if (res && res.isEnded || res === undefined) {
                console.log('播放激励视频结束，给予奖励1')
                this.videoSuccess1 && this.videoSuccess1()
                this.videoEnd1 && this.videoEnd1()
            } else {
                console.log('播放没结束，不给予奖励1')
                this.videoEnd1 && this.videoEnd1()
            }

        })
        this.rewardedVideoAd1.load()
    }
    reLoadVideo() {
        if (sys.platform == sys.Platform.DESKTOP_BROWSER) {
            return
        }
        console.error('videoInde', this.videIndex)
        this.rewardedVideoAd = this.channelObj.createRewardedVideoAd({
            adUnitId: this.getPara('videoAd'),
            success: (code) => {
                console.log("ad demo : loadAndShowVideoAd createRewardedVideoAd success");
            },
            fail: (data, code) => {
                console.log("ad demo : loadAndShowVideoAd createRewardedVideoAd fail: " + data + "," + code);
            },
            complete: () => {
                console.log("ad demo : loadAndShowVideoAd createRewardedVideoAd complete");
            }
        });
        this.rewardedVideoAd.offLoad()
        this.rewardedVideoAd.onLoad(() => {
            console.log('ad demo :ad loaded.')
        })
        let taht = this
        this.rewardedVideoAd.offError()
        this.rewardedVideoAd.onError((e) => {
            console.error('load ad error:' + JSON.stringify(e));
            const errCode = e.errCode
            const errMsg = e.errMsg
            // this.channelObj.showToast({
            //     title: '广告正在加载，请稍后',
            // });

            if (taht.videIndex < 2) {
                taht.videIndex++
            } else {
                taht.videIndex = 0
                console.log("重置广告位index", this.videIndex)
            }
            if (taht.videIndex == 0) {
                console.log("停止", this.videIndex)
                this.channelObj.showToast({
                    title: '广告正在加载，请稍后',
                });
                setTimeout(() => {
                    console.error("重新循环广告")
                    taht.reLoadVideo()
                }, 5000);

            } else {

                console.log("重新reload", this.videIndex)
                taht.reLoadVideo()
                console.error("重新换广告位")
            }
            this.videoEnd && this.videoEnd()

            //  this.rewordVideo = false

            // this.videoError && this.videoError()
        })
        this.rewardedVideoAd.offClose()
        this.rewardedVideoAd.onClose((res) => {
            // if(!this.rewardedVideoAd) return
            // this.rewardedVideoAd.offClose(null);
            console.log('ad onClose: ' + res.isEnded)
            // this.rewardedVideoAd.offLoad(null);
            if (res && res.isEnded || res === undefined) {
                console.log('播放激励视频结束，给予奖励')
                this.videoSuccess && this.videoSuccess()
                this.videoEnd && this.videoEnd()
            } else {
                console.log('播放没结束，不给予奖励')
                this.videoEnd && this.videoEnd()
            }
            this.sendReportVideoActive(res.isEnd)

            // this.rewordVideo = false

        })
        this.rewardedVideoAd.load()

    }
    //由于激励广告要求预加载，可在进入游戏时立即触发上述逻辑。在onLoad触发成功回调时，可以展示视频广告组件。
    //玩家每次点击视频按钮时调用rewardedVideoAd.show()播放广告。在播放期间或者关闭视频前调用rewardedVideoAd.load()请求下一次广告
    showVideo(succ, end = null) {
        if (sys.platform == sys.Platform.DESKTOP_BROWSER) {
            console.log("观看广告")
            succ && succ()
            end && end()
            return
        }

        console.log("观看广告")
        this.rewordVideo = true

        this.videoEnd = end
        this.videoSuccess = succ
        this.rewardedVideoAd.show();
        this.rewardedVideoAd.load()
        setTimeout(() => {
            this.rewordVideo = false
        }, 2000);
    }
    showVideoInterFlag = false
    // showVideoInter(succ, end = null) {
    //     if (cc.sys.platform == cc.sys.DESKTOP_BROWSER) {
    //         console.log("观看广告")
    //         succ && succ()
    //         end && end()
    //         return
    //     }
    //     // if (this.interstitialAd) {

    //     // } else {
    //     //     this.preloadCustomAd()
    //     // }
    //     console.log("观看广告")


    //     this.videoEnd2 = end
    //     this.videoSuccess2 = succ
    //     this.showVideoInterFlag = true
    //     this.rewardedVideoAd2.show();
    //     this.rewardedVideoAd2.load();

    //     //end && end()
    // }

    bannerAD
    bannerAdID
    bannerCanShow = true
    showBanner(isForce?: boolean, styleFn?: any, where?: string): void {
        //console.log("展示banner")
        if (sys.platform == sys.Platform.DESKTOP_BROWSER) {
            console.log("观看banner")

            return
        }
        if (!this.bannerCanShow) {
            return
        }
        this.bannerCanShow = false
        //获取手机详细参数
        let that = this
        var sysInfo = this.channelObj.getSystemInfoSync();
        //console.log("on getSystemInfoSync: success =" + JSON.stringify(sysInfo));
        //获取当前手机屏幕高度(dp)
        var bannerTop = sysInfo.safeArea.height
        this.bannerAD = this.channelObj.createBannerAd({
            // console.log("createBannerAd");          
            adUnitId: this.getPara("bannerId"),
            //adIntervals: 30,
            style: {
                //top需要手机屏幕高度减去广告本身高度
                top: bannerTop - 57,
                left: 0,
                height: 57,
                width: 360,
            }
        });
        setTimeout(function () {
            that.bannerAD.show()
        }, 1000);
        this.bannerAD.onClose(() => {
            setTimeout(() => {
                that.bannerCanShow = true
                that.showBanner()
            }, 30000);
        })
        this.bannerAD.onError(() => {
            setTimeout(() => {
                that.bannerCanShow = true
                that.showBanner()
            }, 30000);
        })
    }


    showBannerAd() {
        console.log(this.bannerAD);
        let that = this
        setTimeout(function () {
            that.bannerAD.show();
        }, 100);
    }



    hideBannerAd() {
        let that = this
        setTimeout(function () {
            that.bannerAD.hide();
        }, 100);
    }


    showHt() {

    }
    interstitialAd = null

    preloadCustomAd(): void {

        const interId = this.getPara('customAd');
        if (!interId) {
            return;
        }
        const hw = this.channelObj;
        console.log('showInter isShow', interId);
        this.interstitialAd = hw.createInterstitialAd({
            adUnitId: interId,
        });
        this.interstitialAd.onError(err => {
            console.log("插屏广告加载失败" + JSON.stringify(err));
            // setTimeout(() => {
            //     this.preloadCustomAd();
            // }, 3000);
        });
        let that = this
        this.interstitialAd.onClose(err => {
            console.log('插屏广告关闭 my');

            that.preloadCustomAd();
            // this.doAction(7, ['my']);
        });
        this.interstitialAd.load();
    }

    playCustom() {

        console.log("播放插屏 播放插屏");
        this.interstitialAd.show().then(() => {
            console.log('插屏广告展示完成');
        }).catch((err) => {
            console.log('插屏广告展示失败' + JSON.stringify(err));
        });

    }
}

